package com.sgb.businessmodule.view.ui.fragment;

import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.databinding.DataBindingUtil;
import androidx.lifecycle.Observer;
import androidx.lifecycle.ViewModelProvider;
import androidx.recyclerview.widget.LinearLayoutManager;

import com.sgb.businessmodule.R;
import com.sgb.businessmodule.databinding.FragmentHomeBusinessChildBinding;
import com.sgb.businessmodule.entity.BusinessRequestEntity;
import com.sgb.businessmodule.entity.HomeBusinessListEntity;
import com.sgb.businessmodule.entity.NotifyRefreshEvent;
import com.sgb.businessmodule.view.ui.adapter.AdapterJumpPush;
import com.sgb.businessmodule.view.ui.adapter.HomeBusinessAdapter;
import com.sgb.businessmodule.viewmodel.HomeBusinessChildModel;
import com.swgk.core.base.AppLazyFragment;
import com.swgk.core.recyclerview.adapter.AdapterOnItemClick;
import com.swgk.core.recyclerview.decoration.RecyclerCustomDecoration;
import com.swgk.core.util.SharedPreferenceUtil;
import com.swgk.core.xrecyclerview.XRecyclerView;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.List;

/**
 * @author 李伟
 * @date 2021/8/10 14:58
 * @Description 商机首页列表界面
 */
public class HomeBusinessChildFragment extends AppLazyFragment {
    private FragmentHomeBusinessChildBinding mBinding;
    private HomeBusinessChildModel mViewModel;

    //商机列表请求entity
    private BusinessRequestEntity requestEntity;
    private boolean isLoadMore = false;
    private int currentPage = 1;

    //商机首页列表Adapter
    private HomeBusinessAdapter homeBusinessAdapter;

    public static HomeBusinessChildFragment newInstance() {
        HomeBusinessChildFragment fragment = new HomeBusinessChildFragment();
        Bundle args = new Bundle();
        fragment.setArguments(args);
        return fragment;
    }

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        mBinding = DataBindingUtil.inflate(inflater, R.layout.fragment_home_business_child, container, false);
        mViewModel = new ViewModelProvider(this).get(HomeBusinessChildModel.class);
        return mBinding.getRoot();
    }

    @Override
    protected void initView() {
        if (requestEntity == null)
            requestEntity = new BusinessRequestEntity();
        LinearLayoutManager layoutManager = new LinearLayoutManager(getActivity());
        mBinding.recyclerView.setLayoutManager(layoutManager);
        mBinding.recyclerView.addItemDecoration(new RecyclerCustomDecoration(0,
                0,
                0,
                getResources().getDimension(R.dimen.dp1)));
        if (homeBusinessAdapter == null) {
            homeBusinessAdapter = new HomeBusinessAdapter(getActivity(), null);
            homeBusinessAdapter.setOnItemClick(new AdapterOnItemClick<HomeBusinessListEntity>() {
                @Override
                public void onItemClick(HomeBusinessListEntity entity, int position) {
                    AdapterJumpPush.getInstance(getActivity(), entity, new AdapterJumpPush.CallBack() {
                        @Override
                        public void doBack() {
                            homeBusinessAdapter.getDatas().remove(entity);
                            homeBusinessAdapter.notifyDataSetChanged();
                        }
                    });
                }
            });
        }
        mBinding.recyclerView.setAdapter(homeBusinessAdapter);
        mBinding.recyclerView.setPullRefreshEnabled(false);
        mBinding.recyclerView.setLoadingListener(new XRecyclerView.LoadingListener() {
            @Override
            public void onRefresh() {
            }

            @Override
            public void onLoadMore() {
                loadData(true);
            }
        });

        //监听获取列表数据返回
        mViewModel.homeBusinessList.observe(this, new Observer<List<HomeBusinessListEntity>>() {
            @Override
            public void onChanged(List<HomeBusinessListEntity> homeBusinessListEntities) {
                showList(homeBusinessListEntities);
            }
        });
    }

    @Override
    public void onStart() {
        super.onStart();
        if (!EventBus.getDefault().isRegistered(this))
            EventBus.getDefault().register(this);
    }

    private void loadData(boolean isLoadMore) {
        if (isAuth()) {
            showEmptyView(false);
            this.isLoadMore = isLoadMore;
            if (isLoadMore) {
                currentPage++;
            } else {
                currentPage = 1;
            }
            requestEntity.setPage(currentPage);
            requestEntity.setLimit(20);
            BusinessRequestEntity.SortFieldBean bean = new BusinessRequestEntity.SortFieldBean();
            bean.setPublishTime(false);
            requestEntity.setSortField(bean);
            mViewModel.requestBusinessListData(requestEntity);
        } else {
            showEmptyView(true);
        }
    }

    @Override
    protected void onLazyLoad() {
        loadData(false);
    }

    public void showList(List<HomeBusinessListEntity> list) {
        if (isLoadMore) {
            if (list != null && list.size() > 0) {
                homeBusinessAdapter.addDatas(list);
            }
            mBinding.recyclerView.setNoMore(mViewModel.isLastPage);
            mBinding.recyclerView.setVisibility(View.VISIBLE);
        } else {
            mBinding.recyclerView.refreshComplete();
            if (list != null && list.size() > 0) {
                mBinding.emptyView.setVisibility(View.GONE);
                homeBusinessAdapter.setDatas(list);
                mBinding.recyclerView.smoothScrollToPosition(0);
                mBinding.recyclerView.setNoMore(mViewModel.isLastPage);
            } else {
                homeBusinessAdapter.clearDatas();
                mBinding.emptyView.setVisibility(View.VISIBLE);
            }
        }
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        EventBus.getDefault().unregister(this);
    }

    /*
     * 刷新商机首页/切换当前城市---刷新当前列表数据
     * */
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEvent(NotifyRefreshEvent event) {
        if (event.isRefresh()) {
            loadData(false);
        }
    }

    /**
     * 商机信息查看权限判断
     *
     * @return ture 符合权限要求 false 否
     */
    public boolean isAuth() {
        List<String> authCompanyList = new ArrayList<>();
        authCompanyList.add("202004302544834");
        authCompanyList.add("1316637963131686912");
        authCompanyList.add("1321724009720713216");
        authCompanyList.add("202007211619262");
        authCompanyList.add("202004302544834");
        authCompanyList.add("202008148048453");
        if (!"".equals(SharedPreferenceUtil.getInstance().getSaveStringData(SharedPreferenceUtil.LOGIN_TOKEN, ""))) {
            int type = SharedPreferenceUtil.getInstance().getSaveIntData(SharedPreferenceUtil.COM_TYPE, 0);
            if (type == 1) {
                String companyNo = SharedPreferenceUtil.getInstance().getSaveStringData(SharedPreferenceUtil.COMPANY_NO, "");
                if (authCompanyList.contains(companyNo)) {
                    return true;
                } else {
                    return false;
                }
            } else {
                return false;
            }
        }
        return false;
    }

    /*
     * 空界面展示
     * */
    private void showEmptyView(boolean flag) {
        if (flag) {
            mBinding.recyclerView.setVisibility(View.GONE);
            mBinding.emptyView.setVisibility(View.VISIBLE);
        } else {
            mBinding.recyclerView.setVisibility(View.VISIBLE);
            mBinding.emptyView.setVisibility(View.GONE);
        }
    }
}
